package com.bancomer.batch.validators.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.bancomer.batch.Constants;
import com.bancomer.batch.MapConstants;
import com.bancomer.batch.pojo.Alert;
import com.bancomer.batch.pojo.FileHelper;
import com.bancomer.batch.pojo.ValidationResult;
import com.bancomer.batch.util.FilesWriter;
import com.bancomer.batch.util.NumberComparator;
import com.bancomer.batch.validators.GeneralValidator;

public class DisableByOptionAlertValidator implements GeneralValidator{
	private StringBuffer condition = new StringBuffer();
	@Override
	public ValidationResult executeValidation(FileHelper fileHelper,
			Object... obj) {
		ValidationResult result = new ValidationResult();
		try {
			result = validateAlertByOptions(fileHelper,(Alert)obj[0]);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setMessage(e.getMessage());
			result.setSucces(false);
		}
		return result;
	}
	
	public ValidationResult validateAlertByOptions(FileHelper fileHelper, Alert alert){
		Map<String,String> alertexcFilter = new HashMap<String,String>();
		FileHelper parameterFile = null;
		ValidationResult result = new ValidationResult();
		FileReader input = null;
		BufferedReader buffer = null;
		File alertexc;
		String positions;
		String names;
		String[] columnsPositions;
		String[] columnsNames;
		String line;
		String load="";
		
		Map<String,int[]> columnPositions = new HashMap<String, int[]>();
		
		try{
			MapConstants properties = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile"));
			final Properties alertConstants = properties.getConstants();
			for(FileHelper file : alert.getOutputFiles()){
				if(file.getName().equals("pigScriptParameters.properties")){
					parameterFile = file;
					break;
				}
			}
			input = new FileReader(parameterFile.getLocalPath()+parameterFile.getName());
			buffer = new BufferedReader(input);
			line=buffer.readLine();
			while(line!=null){
				if(line.contains(fileHelper.getProperties().getProperty("layoutName"))){
					load = line.split("=")[1];
					break;
				}
				line = buffer.readLine();
			}
			buffer.close();
			load = load.replace("com.bancomer.pig.functions.IndexOfLoader", "");
			load = load.replaceAll("[\\(\\'\\ \\)]","");
			positions = load.split("as")[0];
			names = load.split("as")[1];
			columnsPositions = positions.split(",");
			columnsNames = names.split(",");
	
			for(int i=0;i<columnsPositions.length;i++){
				int[] indexPositions = new int[2];
				indexPositions[0]=Integer.valueOf(columnsPositions[i].split("-")[0]);
				indexPositions[1]=Integer.valueOf(columnsPositions[i].split("-")[1]);
				columnPositions.put(columnsNames[i].split(":")[0],indexPositions);
			}
			alertexc = new File(fileHelper.getLocalPath()+fileHelper.getName());
			if(alertexc.exists()==true&&alertexc.length()>0){
				input = new FileReader(fileHelper.getLocalPath()+fileHelper.getName());
				buffer = new BufferedReader(input);	
				line = buffer.readLine();
				while (line != null)   {
					int[] indexPositions;
					indexPositions = columnPositions.get(alertConstants.getProperty("TAB_ALERTEXC_COL3"));
					String alertName = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
					if(alertConstants.getProperty("ALERT_NAME").equals(alertName)){
						indexPositions = columnPositions.get(alertConstants.getProperty("TAB_ALERTEXC_COL1"));
						String deactivationType = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
						switch(Integer.valueOf(deactivationType)){
							case 2: 
								indexPositions = columnPositions.get(alertConstants.getProperty("TAB_ALERTEXC_COL4")); 
								String officeNumber = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
								condition.append("NOT (TRIM($0) == '"+officeNumber+"') AND ");
								break;
							case 3:
								indexPositions = columnPositions.get(alertConstants.getProperty("TAB_ALERTEXC_COL5"));
								String clientNumber = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
								condition.append("NOT (TRIM($6) == '"+clientNumber+"') AND ");
								break;
							case 4:
								indexPositions = columnPositions.get(alertConstants.getProperty("TAB_ALERTEXC_COL6"));
								String contractNumber = line.substring(indexPositions[0],(indexPositions[1]>line.length())?line.length():indexPositions[1]).trim();
								condition.append("NOT (TRIM($1) == '"+contractNumber+"') AND ");
								break;
							default: break;
						}
					}
					line = buffer.readLine();
		    	}
				buffer.close();
			}
			if("".equals(condition.toString().trim())){
				condition.append("NOT (TRIM($0) == '') AND NOT (TRIM($6) == '') AND NOT (TRIM($1) == '')");
			}
			else{
				condition.delete(condition.length()-5,condition.length());
			}
			alertexcFilter.put("alertexcFilter", condition.toString());
			FilesWriter.writePropertiesFile(parameterFile,alertexcFilter);
		}
		catch(Exception e){
			result.setMessage("Class: DisableByOptionValidator - "+e.getMessage());
			result.setSucces(false);
		}
		return result;
	}
}
